let pageSize = 5;
let page = 1;
let teacherName = $.cookie("teacherName");
const creator = teacherName;
let totalData = 0;
let pollingInterval = null;
let lastDataHash = '';
let isPollingPaused = false;

// 初始化函数
function initExamManager() {
    // 初始加载数据
    loadData();

    // 启动轮询
    startPolling();

    // 设置事件监听
    setupEventListeners();
}

// 主数据加载函数
function loadData() {
    if (isPollingPaused) return;

    const startTime = performance.now();

    // 并行请求数据和总数
    Promise.all([
        fetchPageData(),
        fetchTotalCount()
    ]).then(() => {
        const endTime = performance.now();
        console.log(`数据加载完成，耗时: ${(endTime - startTime).toFixed(2)}ms`);
    }).catch(error => {
        console.error("数据加载错误:", error);
    });
}

// 获取分页数据
function fetchPageData() {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: "/exam/getExam",
            type: "POST",
            dataType: "json",
            data: {
                page,
                name: $(".search-lesson-plan").val(),
                pageSize,
                creator
            },
            success: function(res) {
                const newHash = calculateDataHash(res.data.rows);
                if (newHash !== lastDataHash) {
                    lastDataHash = newHash;
                    renderTable(res.data.rows);
                }
                resolve();
            },
            error: function(xhr, status, error) {
                console.error("加载数据失败:", error);
                reject(error);
            }
        });
    });
}

// 获取总数据量
function fetchTotalCount() {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: "/exam/getExam",
            type: "POST",
            dataType: "json",
            data: {
                page,
                pageSize,
                creator,
                name: $(".search-lesson-plan").val(),
            },
            success: function(res) {
                totalData = res.data.total;
                renderPagination();
                resolve();
            },
            error: function(xhr, status, error) {
                console.error("获取总数失败:", error);
                reject(error);
            }
        });
    });
}

// 渲染表格数据（优化版）
function renderTable(data) {
    const $tbody = $(".tbody");
    const fragment = document.createDocumentFragment();

    data.forEach(item => {
        const row = document.createElement("tr");
        row.innerHTML = `
            <td>${item.id}</td>
            <td>${item.name}</td>
            <td>${item.createtime}</td>
            <td>${item.creator}</td>
            <td>${item.examtime}</td>
            <td>
                <span class="status-badge" data-status="${item.status}">${item.status}</span>
            </td>
            <td>
                <button class="action-btn preview-exam" data-id="${item.id}" title="预览">
                    <i class="fas fa-eye"></i> 预览
                </button>
                <button class="action-btn publish-exam" data-id="${item.id}" title="发布考试">
                    <i class="fas fa-paper-plane"></i> 发布考试
                </button>
            </td>
        `;
        fragment.appendChild(row);
    });

    // 使用requestAnimationFrame优化渲染
    requestAnimationFrame(() => {
        $tbody.empty().append(fragment);
    });
}

// 渲染分页控件
function renderPagination() {
    const totalPages = Math.ceil(totalData / pageSize);
    const $pageNumber = $(".page-number");
    const fragment = document.createDocumentFragment();

    // 总是显示第一页
    if (totalPages >= 1) {
        const btn = createPageButton(1);
        fragment.appendChild(btn);
    }

    // 显示前导省略号（如果需要）
    if (page - 2 > 2) {
        const ellipsis = document.createElement("span");
        ellipsis.textContent = "...";
        fragment.appendChild(ellipsis);
    }

    // 显示当前页附近的页码
    for (let j = Math.max(2, page - 2); j <= Math.min(totalPages - 1, page + 2); j++) {
        const btn = createPageButton(j);
        fragment.appendChild(btn);
    }

    // 显示后导省略号（如果需要）
    if (page + 2 < totalPages - 1) {
        const ellipsis = document.createElement("span");
        ellipsis.textContent = "...";
        fragment.appendChild(ellipsis);
    }

    // 总是显示最后一页（如果有）
    if (totalPages > 1) {
        const btn = createPageButton(totalPages);
        fragment.appendChild(btn);
    }

    // 使用requestAnimationFrame优化渲染
    requestAnimationFrame(() => {
        $pageNumber.empty().append(fragment);
        updateActivePage();
    });
}

// 创建分页按钮
function createPageButton(pageNum) {
    const btn = document.createElement("button");
    btn.className = `page-btn ${pageNum === page ? 'active' : ''}`;
    btn.id = pageNum;
    btn.textContent = pageNum;
    return btn;
}

// 更新活动页样式
function updateActivePage() {
    $(".page-btn").removeClass("active");
    $(`.page-btn[id="${page}"]`).addClass("active");
}

// 计算数据哈希（用于判断数据是否变化）
function calculateDataHash(data) {
    return JSON.stringify(data.map(item => ({
        id: item.id,
        status: item.status
    })));
}

// 启动轮询
function startPolling() {
    if (pollingInterval) clearInterval(pollingInterval);

    // 初始立即加载
    loadData();

    // 设置轮询间隔（2秒）
    pollingInterval = setInterval(() => {
        if (!isPollingPaused) {
            loadData();
        }
    }, 5000);

    // 当页面获得焦点时立即更新
    $(window).on("focus", () => {
        if (!isPollingPaused) {
            loadData();
        }
    });
}

// 暂停轮询
function pausePolling() {
    isPollingPaused = true;
}

// 恢复轮询
function resumePolling() {
    isPollingPaused = false;
    loadData(); // 立即加载一次
}

// 设置事件监听
function setupEventListeners() {
    // 分页点击
    $(document).on("click", ".page-btn", function() {
        page = Number($(this).text());
        loadData();
    });

    // 上一页
    $(".front").on("click", function() {
        if (page > 1) {
            page--;
            loadData();
        }
    });

    // 下一页
    $(".next").on("click", function() {
        if (page < Math.ceil(totalData / pageSize)) {
            page++;
            loadData();
        }
    });

    // 首页
    $(".first").on("click", function() {
        page = 1;
        loadData();
    });

    // 尾页
    $(".end").on("click", function() {
        page = Math.ceil(totalData / pageSize);
        loadData();
    });

    // 指定页码跳转
    $(".change").on("click", function() {
        const newPage = parseInt($(".page-input").val());
        if (!isNaN(newPage) && newPage > 0 && newPage <= Math.ceil(totalData / pageSize)) {
            page = newPage;
            loadData();
        }
    });

    // 切换每页显示数量
    $(".page-size-select").on("change", function() {
        pageSize = Number($(this).val());
        page = 1;
        loadData();
    });

    // 生成按钮
    $(".generate-btn").on("click", function() {
        pausePolling();
        location.href = "examGenerate";
    });

    // 搜索按钮
    $(".search-btn").on("click", function() {
        page = 1;
        loadData();
    });

    // 预览考试
    $(".tbody").on("click", ".preview-exam", function() {
        pausePolling();
        const examId = $(this).attr("data-id");
        $.cookie("examId", examId);
        location.href = "examDetail";
    });

    // 发布考试
    $(".tbody").on("click", ".publish-exam", function() {
        const status = $(this).parent().prev().find(".status-badge").text().trim();
        const id = $(this).attr("data-id");

        if (status === "未开始") {
            pausePolling();

            $.ajax({
                url: "/exam/updateExambyId",
                type: "POST",
                data: { id },
                success: function(res) {
                    $(".alert-success").fadeIn().delay(1200).fadeOut();
                    resumePolling();
                },
                error: function() {
                    resumePolling();
                }
            });
        }
    });

    // 页面离开时停止轮询
    $(window).on("beforeunload", function() {
        clearInterval(pollingInterval);
    });
}

// 初始化应用
$(document).ready(function() {
    initExamManager();
});